package com.fh.controller.system.excel;

import com.fh.controller.base.BaseController;
import com.fh.model.Page;
import com.fh.model.loan.CallLoanInfoDto;
import com.fh.model.system.ExcelRecord;
import com.fh.service.loantaskimpl.LoanTaskOverServiceImpl;
import com.fh.service.loantaskimpl.LoanTaskToBeServiceImpl;
import com.fh.service.loantaskimpl.LoanTaskUnderServiceImpl;
import com.fh.service.system.excel.ExcelService;
import com.fh.service.system.user.UserService;
import com.fh.util.JsonUtil;
import com.fh.util.PageData;

import com.fh.util.UserUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.util.PoiMergeCellUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * Created by dell、 on 2017/5/13.
 */
@Controller
@RequestMapping("/excel")
public class ExcelController extends BaseController {

    @Autowired
    private LoanTaskOverServiceImpl loanTaskOverService;
    @Autowired
    private LoanTaskUnderServiceImpl loanTaskUnderService;
    @Autowired
    private LoanTaskToBeServiceImpl loanTaskToBeService;
    @Autowired
    private UserService userService;

    /**
     * 待催收excel导出
     * @param response
     * @param mapList
     * @param model
     * @throws IOException
     */
    @RequestMapping(value="/export",produces="text/html;charset=UTF-8")
    public void exportExcel(HttpServletResponse response,String mapList, Model model)
            throws IOException {
        TemplateExportParams params = new TemplateExportParams(
                "static/excel/doc/逾期客户表-待催收.xlsx");
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String,Object>> maps = new ArrayList<>();
        if(mapList != null){
            maps = (List<Map<String, Object>>) JsonUtil.jsonArrToList(
                    new String(mapList.getBytes("ISO-8859-1"), "UTF-8"));
        }
        Page page = new Page();
        PageData pageData =  loanTaskToBeService.setPdWithTrim(this.getPageData());
        //设置数据权限
        page.setPd(UserUtils.setDataRole(pageData,userService));
        List<PageData> pageDataList = loanTaskToBeService.getToBeList(page);//获取当前页数据
        List<Map<String,Object>> dataMap = new ArrayList<>();
        Iterator iterator1 = pageDataList.iterator();
        String key = "repayment_id";
        while (iterator1.hasNext()){//"repayment_id" -> "6"
            PageData data = (PageData)iterator1.next();
            for (Map<String,Object> obj : maps){
                if((data).get(key).equals(obj.get(key))){
                    data.put("periods",data.get("period")+"/" + data.get("period_total"));
                    dataMap.add(data);
                }
            }
        }
        map.put("mapList", dataMap);
        //准备导出
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        //输出Excel文件
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode("逾期客户表.xls", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();//刷新
        outputStream.close();
    }

    /**
     * 催收中、已结案excel导出
     * @param response
     * @param flag{0:催收中,1:已结案}
     * @param model
     * @throws IOException
     */
    @RequestMapping(value="/exportCallInfo",produces="text/html;charset=UTF-8")
    public void exportCallInfo(HttpServletResponse response,String flag, Model model,Page page,String[] ids)
            throws IOException {
    	TemplateExportParams params = new TemplateExportParams(
                "static/excel/doc/逾期客户表-已结案.xlsx");
    	 Map<String, Object> map = new HashMap<String, Object>();
         List<CallLoanInfoDto> list = new ArrayList();
         /* if(mapList != null){
             maps = (List<Map<String, Object>>) JsonUtil.jsonArrToList(
                     new String(mapList.getBytes("ISO-8859-1"), "UTF-8"));
         }
         map.put("infolist", maps);*/
    	 /*if(ids != null || 0 != ids.length){
    		 map.put("overId", ids);
    		 list=loanTaskOverService.callLoanOverExl(map);
    	 }*/
    	 map.put("infolist", list);
        //准备导出
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        //输出Excel文件
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode("逾期客户表.xls", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();//刷新
        outputStream.close();
    }


    /***
     * 导出 excel 例子
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportDemo")
    public void exportExcelDemo(HttpServletResponse response,  String mapList) throws IOException {
        List<Map<String,String>> maps = new ArrayList<>();
        if(mapList != null){
            maps = (List<Map<String, String>>) JsonUtil.jsonArrToList(mapList);
        }
        // 可以捕获内存缓冲区的数据，转换成字节数组
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet = wb.createSheet("成绩表");
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个


        HSSFRow row1 = sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell cell = row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("学员考试成绩一览表");
        //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        //在sheet里创建第二行
        HSSFRow row2 = sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("姓名");
        row2.createCell(1).setCellValue("班级");
        row2.createCell(2).setCellValue("笔试成绩");
        row2.createCell(3).setCellValue("机试成绩");
        //在sheet里创建第三行
        HSSFRow row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("李明");
        row3.createCell(1).setCellValue("As178");
        row3.createCell(2).setCellValue(87);
        row3.createCell(3).setCellValue(78);
        wb.write(out);

        //输出Excel文件
        byte[] bytes = out.toByteArray();
        response.setContentType("application/x-msdownload");
        response.setContentLength(bytes.length);
        response.setHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode("成绩表.xls", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();//刷新
        outputStream.close();

    }

    /**
     * easyPoi demo
     * @param response
     * @throws IOException
     */
    @RequestMapping("/easyPoi")
    public void easyPoi(HttpServletResponse response) throws IOException {
        TemplateExportParams params = new TemplateExportParams(
                "static/excel/doc/foreach.xlsx");
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> testMap = new HashMap<String, Object>();

            testMap.put("id", "xman");
            testMap.put("name", "小明" + i);
            testMap.put("sex", "1");
            mapList.add(testMap);
        }
        map.put("maplist", mapList);
        //本来导出是专业那个
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        //输出Excel文件
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode("成绩表.xls", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();//刷新
        outputStream.close();
    }
	
	@RequestMapping("/isOutExcelSuccess")
	@ResponseBody
	public boolean isOutExcelSuccess(String key){
		HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest().getSession();
		return (boolean) session.getAttribute(key);
	}
	
	@RequestMapping("/removeExcelFlag")
	@ResponseBody
	public String remove(String key){
		HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest().getSession();
		session.removeAttribute(key);
		return "clear session success;";
	}
}

